package com.javalong.affairs.adapter;

import java.util.ArrayList;
import java.util.List;

import android.R.bool;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

import com.javalong.affairs.R;
import com.javalong.affairs.model.Dept;

public class DeptAdapter extends BaseAdapter {
	private List<Dept> selectedDepts;
	private boolean hasCheck;

	public DeptAdapter(Context context, List<Dept> deptList) {
		this(context, deptList, true);
	}

	public DeptAdapter(Context context, List<Dept> deptList, boolean hasCheck) {
		super(context, deptList);
		selectedDepts = new ArrayList<Dept>();
		this.hasCheck = hasCheck;
	}

	public List<Dept> getSelectedDepts() {
		return selectedDepts;
	}

	@Override
	public void notifyDataSetChanged() {
		super.notifyDataSetChanged();
		selectedDepts.clear();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final Dept dept = (Dept) getItem(position);
		ViewHolder holder;
		if (convertView != null) {
			holder = (ViewHolder) convertView.getTag();
		} else {
			holder = new ViewHolder();
			convertView = mInflater.inflate(R.layout.item_dept, null);
			holder.tv_dept = (TextView) convertView.findViewById(R.id.tv_dept);
			holder.cb_dept = (CheckBox) convertView.findViewById(R.id.cb_dept);
			if (!hasCheck) {
				holder.cb_dept.setVisibility(View.GONE);
			}

			convertView.setTag(holder);
		}

		if (dept != null) {
			holder.tv_dept.setText(dept.name);
			holder.cb_dept
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {
						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							if (isChecked) {
								if (!selectedDepts.contains(dept)) {
									selectedDepts.add(dept);
								}
							} else {
								if (selectedDepts.contains(dept)) {
									selectedDepts.remove(dept);
								}
							}
						}
					});
			if (selectedDepts.contains(dept)) {
				holder.cb_dept.setChecked(true);
			} else {
				holder.cb_dept.setChecked(false);
			}
		}
		return convertView;
	}

	class ViewHolder {
		CheckBox cb_dept;
		TextView tv_dept;
	}

	public enum Type {
		DELEGATE, RECEIVER
	}
}
